package no.ffi.gismoidm.pubsub;

import java.util.Iterator;
import java.util.List;

/**
 * Subscription from a group of client, aggregated by the message router (MR)
 * and flooded around in the MR network. The timestamp is for loop termination
 * during flooding.
 * @author anders
 */
public class AggregateSubscription implements java.io.Serializable {
    List<Subscription> aggSub;
    String mrID; // Unique message router ID
    long timestamp; // Timestamped at creation
    
    public AggregateSubscription(List<Subscription> subscriptions, String id) {
        // Reduction algorithms can be applied here
        aggSub = subscriptions;
        mrID = id;
        timestamp = System.currentTimeMillis();
    }
    
    /* Constructor for "neighbor marker". It is constructed when a new
     * neighbor MR is connected, and is inserted into the forwarding table
     * in order for it to receive aggSub uppdates.
     */
    public AggregateSubscription(String id) {
        aggSub = null;
        mrID = id;
        timestamp = 0;
    }
    
    /*
     * Check an aggregate subscription for forwarding match
     * If one of the subscription elements, end the loop and
     * return true
     */
    public boolean forwardMatch(Publication pub) {
        if (aggSub == null) return false; // Exclude "markers"
        Iterator <Subscription> it = aggSub.iterator();
        while (it.hasNext()) {
            Subscription s1 = it.next();
            if (s1.forwardMatch(pub)) return true;
        }
        return false;
    }
    
    // Return true if this a "marker" aggSub, in which case it should
    // not be flooded to other MRs
    public boolean isMarker() {
        return aggSub==null;
    }
    
    
    
}


